package com.timothy.android.util;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import android.content.Context;
import android.util.Log;
import android.view.Gravity;
import android.widget.Toast;


public class ToastUtil {
	private static final String LOG_TAG = "ToastUtil";
	
	private Toast toast;
	private Field field;
	private Object obj;
	private Method showMethod, hideMethod;

	public ToastUtil(Context context,String displayStr) {
		// 创建Toast对象
		toast = Toast.makeText(context, displayStr, 1);
		toast.setGravity(Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL,0, 0);

		// 利用反射技术拿到mTN对象
		reflectionTN();
	}
	
	public void showToast(){
		try {
			showMethod.invoke(obj, null);
		} catch (IllegalArgumentException e) {
			Log.i(LOG_TAG,e.getMessage());
		} catch (IllegalAccessException e) {
			Log.i(LOG_TAG,e.getMessage());
		} catch (InvocationTargetException e) {
			Log.i(LOG_TAG,e.getMessage());
		}
		// 调用TN对象的show()方法，显示toast
	}
	
/*	public void showToast(final int time) {
		Thread timeThread = new Thread() {
			public void run() {
				try {
					Thread.sleep(time);
				} catch (InterruptedException e) {
					Log.i(LOG_TAG, e.getMessage());
				}
				try {
					hideMethod.invoke(obj, null);
				} catch (IllegalArgumentException e) {
					Log.i(LOG_TAG,e.getMessage());
				} catch (IllegalAccessException e) {
					Log.i(LOG_TAG,e.getMessage());
				} catch (InvocationTargetException e) {
					Log.i(LOG_TAG,e.getMessage());
				}
			}
		};
		
		timeThread.start();
		// 调用TN对象的show()方法，显示toast
	}*/
	
	public void closeToast(){
		try {
			hideMethod.invoke(obj, null);
		} catch (IllegalArgumentException e) {
			Log.i(LOG_TAG,e.getMessage());
		} catch (IllegalAccessException e) {
			Log.i(LOG_TAG,e.getMessage());
		} catch (InvocationTargetException e) {
			Log.i(LOG_TAG,e.getMessage());
		}// 调用TN对象的hide()方法，关闭toast
	}

	private void reflectionTN() {
		try {
			field = toast.getClass().getDeclaredField("mTN");
			field.setAccessible(true);
			obj = field.get(toast);
			showMethod = obj.getClass().getDeclaredMethod("show", null);
			hideMethod = obj.getClass().getDeclaredMethod("hide", null);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
